package developerworks.jetty6;

import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.*;
import java.io.Serializable;

public class CrudMessage implements Serializable{
	private String status = "create";
	private String to = "";
	private String domain_name = "moschelrules.com";
	private String call_id;
	private static Pattern pattern = Pattern.compile("([^@]*)@(.*)");
	private static Pattern domainp = Pattern.compile("https?://(?:www\\.)?([^/]*)([^#\\?]*)");
	public void create(){
		status = "create";
		//created.add(this);
	}
	
	public void destroy(){
		status = "destroy";
	}
	public void update(){
		status = "update";
	}
	public JSONObject toJson() throws JSONException {
		return new JSONObject();
	}
	public String getStatus(){
		return status;
	}
	public String json() throws JSONException {

		String name =  this.getClass().getSimpleName();
		JSONObject jsonObj = new JSONObject();

		JSONObject jsonObj2 = new JSONObject();
		
		
		JSONArray arr = new JSONArray();

		arr.put(toJson());
		jsonObj2.put(status, arr);
		
		jsonObj.put(name, jsonObj2);

		return jsonObj.toString();
	}
	public void setTo(String t){
		to = t;
		Matcher matcher = pattern.matcher(to);
		boolean matchFound = matcher.find();
		if(matchFound){
			call_id = matcher.group(1).toLowerCase();
			domain_name = matcher.group(2).toLowerCase();
		}else{
			System.out.println("SendToError");
		}
	}
	
	public void sendTo(String t){
		to = t;
		Matcher matcher = pattern.matcher(to);
		boolean matchFound = matcher.find();
		if(matchFound){
			call_id = matcher.group(1).toLowerCase();
			domain_name = matcher.group(2).toLowerCase();
			ApplicationAddressBook.send( this );
		}else{
			System.out.println("SendToError");
		}
	}
	public void sendToDomain(String d){
		
		to = "@"+d;
		domain_name = d;
		Timey t = new Timey();
		System.out.println("publishing: "+d);
		subscriber.publish( this );
		t.end("CRUD_sendToDomain");
	}
	public boolean isGroup(){
		return call_id == null || call_id.length() == 0;
	}
	public String callID(){
		return call_id;
	}
	public String domainName(){
		return domain_name;
	}
	static public EventSubscriber subscriber = new EventSubscriber();
}
